/**
 * Copyright (c) 2012 Axa Holding Belgium, SA. All rights reserved.
 * This software is the confidential and proprietary information of the AXA Group.
 */
package chabernac.android.wordbattle.paint.animation;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import chabernac.android.tools.SingleObjectQueue;
import chabernac.android.view.AnimationView;
import chabernac.android.wordbattle.paint.DrawableComposite;
import chabernac.android.wordbattle.paint.iDrawable;
import chabernac.android.wordbattle.paint.boggle.WordDrawable;

public class ExplodingTextAnimator {
  private final String myText;
  private iDrawable myBackGroundDrawable;
  private final SingleObjectQueue<iDrawable> myDrawableQueue;
  private final ScheduledExecutorService myExecutorService = Executors.newScheduledThreadPool( 1 );
  private final float myStartTextSize = 50;
  private final float myEndTextSize = 1600;
  private ScheduledFuture myTask = null;
  private long myStartTime;
  private final float myDuration = 1500; 
  

  public ExplodingTextAnimator( String aText, iDrawable aBackGroundDrawable, SingleObjectQueue<iDrawable> aDrawableQueue ) {
    super();
    myText = aText;
    myBackGroundDrawable = aBackGroundDrawable;
    myDrawableQueue = aDrawableQueue;
  }

  public void start(){
    myStartTime = System.currentTimeMillis();
    myTask = myExecutorService.scheduleAtFixedRate( new ExplodingText(), 0, AnimationView.DELAY, TimeUnit.MILLISECONDS );
  }
  
  private iDrawable getDrawable(float aFontSize){
    DrawableComposite theComposite = new DrawableComposite();
    theComposite.addDrawable( myBackGroundDrawable );
    if(aFontSize < myEndTextSize){
      theComposite.addDrawable( new WordDrawable( myText, aFontSize ) );
    } else {
      myTask.cancel( false );
    }
    return theComposite;
  }

  public class ExplodingText implements Runnable {
    @Override
    public void run() {
      try{
        float theEllapsedTime = System.currentTimeMillis() - myStartTime;
        
        float theCurrentFontSize = myStartTextSize + (myEndTextSize * (float)Math.pow(theEllapsedTime/myDuration,6));
       
        myDrawableQueue.put( getDrawable( theCurrentFontSize ) );
        
        /*
        if(theEllapsedTime > myDuration){
          myTask.cancel( false );
        }
        */
      }catch(Throwable e){
        //we do not want the animation thread to get stuck
        //so whenever something happens stop the task
        myTask.cancel( true );
      }
    }
  }

  public void setBackGroundDrawable( iDrawable aBackGroundDrawable ) {
    myBackGroundDrawable = aBackGroundDrawable;
  }
}
